#include "./draw_hot_task.h"
#include "../heat_driver/ctrl.h"
#include "../heat_driver/sensor.h"
#include "../cfg/heat_info.h"

namespace heat_task {

using namespace heat_driver;
using namespace cfg;

DrawHotTask drawHotTask;

void DrawHotTask::init_start() {
    m_mq.init();
    m_flags.init();
    start();
}

void DrawHotTask::run() {

    for (;;) {
        switch (m_state) {
            case State::IDLE: do_idle(); break;
            case State::WORK: do_work(); break;
            case State::STOP: do_stop(); break;
            case State::TIMEOUT:
            case State::FAIL: do_fail(); break;
        }
    }
}

void DrawHotTask::do_idle() {

    for (;;) {

        if (sensor.is_tank_low() && (!sensor.is_hot_high())) {
            m_state = State::WORK;
            break;
        }

        if (wait(500)) {
            break;
        }
    }
}

void DrawHotTask::do_work() {

    uint32_t time_count = 0;
    ctrl.open(Ctrl::Parts::DRAW_PUMP);
    for (;;) {
        if ((!sensor.is_tank_low()) || sensor.is_hot_high()) {
            m_state = State::IDLE;
            goto finish;
        }

        if (wait(500)) {
            goto finish;
        }
        time_count += 500;

        if (time_count >= heatInfo->hot_draw_time) {
            m_state = State::TIMEOUT;
            goto finish;
        }
    }

finish:
    ctrl.close(Ctrl::Parts::DRAW_PUMP);
}

void DrawHotTask::do_fail() {
    wait();
}

void DrawHotTask::do_stop() {
    m_flags.set_flags(FLAG_STOP);
    wait();
}

}
